package com.example.controller;

import com.example.exception.MyException;
import com.example.pojo.Query;
import com.example.pojo.User;
import com.example.service.UserService;
import com.example.utils.Page;
import com.example.utils.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/selectAllUser")
    public Result selectAllUser(Query query){
        Page<User> page = new Page<>(query.getPageNum(),query.getPageSize(),userService.selectUserCount(query.getRealName()));
        page.setList(userService.selectAllUser(query.getRealName(),page.getStart(),query.getPageSize()));
        Map<String,Object> map=new HashMap<>();
        map.put("list", page.getList());
        map.put("count", page.getTotalCount());//总条数
        map.put("pageSize", query.getPageSize());//每页显示几条
        map.put("pageNum", query.getPageNum());//当前页码
        return new Result<>("200", "查询成功", map);
    }

    @GetMapping("/selectUserById")
    public Result selectUserById(int id){
        User user=userService.selectUserById(id);
        Map<String,Object> map=new HashMap<>();
        if (user!=null){
            map.put("code", 200);
            map.put("data", user);
            map.put("msg", "查询成功");
        }else {
            map.put("code", 444);
            map.put("data", null);
            map.put("msg", "查询失败");
        }
        return new Result<>("222", "调用成功", map);
    }

    @PostMapping("/updateUser1")
    public Result updateUser1(@RequestBody User user){
        if(userService.selectUserById(user.getId()).getStatus()==1){
            throw new MyException("444", "该用户已解冻");
        }
        if (userService.updateUser1(user) <= 0) {
            throw new MyException("444", "修改失败");
        }
        return new Result<>("200", "修改成功");
    }

    @PostMapping("/updateUser2")
    public Result updateUser2(@RequestBody User user){
        if(userService.selectUserById(user.getId()).getStatus()==0){
            throw new MyException("444", "该用户已冻结");
        }
        if (userService.updateUser2(user) <= 0) {
            throw new MyException("444", "修改失败");
        }
        return new Result<>("200", "修改成功");
    }
}
